package com.smzd.framework.system.actions;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.smzd.framework.annotation.Access;
import com.smzd.framework.core.actions.AbstractMeetingOwnedController;
import com.smzd.framework.core.business.IFGService;
import com.smzd.framework.exceptions.UsernameAlreadyExistsException;
import com.smzd.framework.system.business.GroupService;
import com.smzd.framework.system.business.UserService;
import com.smzd.framework.system.domain.Meeting;
import com.smzd.framework.system.domain.Role;
import com.smzd.framework.system.domain.User;
import com.smzd.framework.utils.JsonHelper;
import com.smzd.framework.utils.MeetingSessionHolder;
import com.smzd.framework.utils.Privilege;
import com.smzd.framework.utils.db.ORPage;

@Controller
@RequestMapping("/system/users")
@Access({ Role.TAG_ROLE_USER_MANAGER, Role.TAG_ROLE_USER_OWNER })
public class UserController extends AbstractMeetingOwnedController<User> {
    @Autowired
    UserService service;
    @Autowired
    GroupService groupService;

    @Override
    protected IFGService<User> getService() {
        return service;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @Override
    public String toAddPage(Map<String, Object> model, User elem, BindingResult result) throws Exception {
        return super.toAddPage(model, elem, result);
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String postAddData(Map<String, Object> model,
    		@RequestParam(value = "avatar_file", required = false) MultipartFile avatar_file,
    		User elem, BindingResult result) throws Exception {
        if (elem.getType() == User.USER_TYPE_MEETING_OWNER) {
            Privilege p = MeetingSessionHolder.getPrivilege();
            if (p == null || p.hasTag(Role.TAG_ROLE_USER_OWNER) != 1) {
                throw new Exception("你无权建立会务所有者！");
            }
        }
        elem.setOwner(getOwner());
        service.register(elem, avatar_file);
        return JsonHelper.getSuccessJsonString("id", elem.getId());
    }

    @RequestMapping(method = RequestMethod.GET)
    @Override
    public String toListPage(Map<String, Object> model, User elem, BindingResult result) throws Exception {
        return super.toListPage(model, elem, result);
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    @Override
    public String getListData(Map<String, Object> model, ORPage<Meeting, User> page, BindingResult result)
            throws Exception {
        return super.getListData(model, page, result);
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    @Override
    public String toEditPage(Map<String, Object> model, User elem, BindingResult result) throws Exception {
        elem = service.getItemById(elem.getId());
        return super.toEditPage(model, elem, result);
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    @Override
    public String postEditData(Map<String, Object> model, User elem, BindingResult result) throws Exception {
        if (elem.getType() == User.USER_TYPE_MEETING_OWNER) {
            Privilege p = MeetingSessionHolder.getPrivilege();
            if (p == null || p.hasTag(Role.TAG_ROLE_USER_OWNER) != 1) {
                throw new Exception("你无权修改会务所有者！");
            }
        }
        return super.postEditData(model, elem, result);
    }

    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ResponseBody
    @Override
    public String postRemoveData(Map<String, Object> model, User elem, BindingResult result) throws Exception {
        return super.postRemoveData(model, elem, result);
    }

    /**
     * 这个方法用在创建Meeting的时候，选择合适的owner。<br>
     * 原先是写死的，只能从meeting0的用户中选，但实际上，应该从当前操作用户所在的meeting当中选。<br>
     * 由于meeting的创建权限赋给了普通管理员（1），而不是会务所有者类型的管理员（2），因此，使用当前用户所在的meeting是合适的。
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list/owners", method = RequestMethod.POST)
    @Access(Role.TAG_ROLE_USER_OWNER)
    @ResponseBody
    public String getOwnersListData() throws Exception {
        Meeting meeting = MeetingSessionHolder.getMeeting();
        return service.getOwnersListInJson(meeting.getId());
    }
    
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @Access
    public String toRegistryPage(Map<String, Object> model, User user) throws UsernameAlreadyExistsException {
        user.setId(null);
        service.register(user);
        return "redirect:/workspace/success";
    }
    @RequestMapping(value = "/bygroups", method = RequestMethod.POST)
    @ResponseBody
    public String getUsersWithGroups(@RequestParam("gid") int[] gids)
            throws Exception {
    	Meeting meeting = MeetingSessionHolder.getMeeting();
        return service.getUsersWithGroups(gids, meeting);
    }
}
